package auntie.production.app2;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import auntie.production.app2.db.auntie_production_app_db.production_details;
import auntie.production.app2.db.auntie_production_app_db.productions;
import auntie.production.app2.net.mysql_bakery;
import auntie.production.app2.svc.s1;

public class Page3 extends s1 {

    private static final String LOG = Page3.class.getName();

    public static final String PAGE3_BUNDLE_TIME = "time";
    public static final String PAGE3_BUNDLE_STR_PRODUCT = "product";
    public static final String PAGE3_BUNDLE_STR_STICKER = "sticker";

    TimePicker tp_time;
    AutoCompleteTextView actv_product;
    EditText et_sticker;
    Button btn_go1;
    AlertDialog alert_dialog;
    ArrayAdapter<String> p_adapter;
    ProgressDialog progressDialog;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page3);

        tp_time = (TimePicker) findViewById(R.id.tp_time);
        actv_product = (AutoCompleteTextView) findViewById(R.id.actv_product);
        p_adapter = new ArrayAdapter<String>(this, R.layout.list_product);

        actv_product.setAdapter(p_adapter);

        et_sticker = (EditText) findViewById(R.id.et_sticker);
        btn_go1 = (Button) findViewById(R.id.btn_go1);

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("loading products...");
        
        
        
        // look_through_the_server();
        actv_product.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable s) {
                // validation goes here
                // look_through_the_server();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // TODO Auto-generated method stub

            }
        });
        actv_product.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN)
                        && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Perform action on key press
                    actv_product.clearFocus();
                    et_sticker.requestFocus();
                    return true;
                }

                return false;
            }
        });

        actv_product.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                actv_product.clearFocus();
                et_sticker.requestFocus();
            }

        });

        btn_go1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                on_go1();
            }
        });

        hlp_clean();
    }
    
    
    private class LookProductTask extends AsyncTask<Void, Void, Integer> {

        @Override
        protected void onPreExecute() {
            progressDialog.show();
        }

        @SuppressWarnings("finally")
		@Override
        protected Integer doInBackground(Void... params) {

        	try {
                mysql_bakery.mysql_find_products(p_adapter);
            } catch (Exception e) {
                Toast.makeText(Page3.this, "No bakery connection", 2000).show();
            } finally {
            	return 0;
            }
           
        }

        @Override
        protected void onPostExecute(Integer v) {
            progressDialog.dismiss();
        }

    }


    private void hlp_refresh_actv_product() {
        actv_product.setAdapter(p_adapter);
    }

    private void look_through_the_server() {
        String start_with = actv_product.getText().toString();
        Log.i(LOG, start_with);

        String result = "";
        // the year data to send
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("starts_with", ""));

        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://192.168.2.103/get_bakery_products");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);

            StringBuilder sb = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            is.close();
            result = sb.toString();
            Log.i(LOG, result);

            p_adapter.clear();
            JSONArray jArray = new JSONArray(result);

            for (int i = 0; i < jArray.length(); i++) {

                JSONObject json_data = jArray.getJSONObject(i);
                String product_name = json_data.getString("product_name");
                Log.i(LOG, product_name);
                p_adapter.add(product_name);
            }

        } catch (Exception e) {
            Log.e(LOG, "Error parsing data " + e.toString());
        } finally {
            hlp_refresh_actv_product();
        }
    }

    @Override
    public void onBackPressed() {
        // do nothing
    }

    private void hlp_process_product_entry(Date time, String product,
            String sticker) {

        // List<Product> items = lvadp_products.items;

        String p_product = "([\\d|\\s|\\w|%|/|-]*)([@])([0-9]*)";
        Matcher matcher = Pattern.compile(p_product).matcher(product);
        matcher.find();
        String product_name = matcher.group(1);
        String s_prc = matcher.group(3);
        double prc = Double.parseDouble(s_prc);

        String p_sticker1 = "(\\d*)";
        String p_sticker2 = "(\\d*)([\\*|x|X])(\\d*)";
        String p_sticker3 = "(\\d*)([\\*|x|X])(\\d*)(\\+)(\\d*)";
        String[] ps = new String[] { p_sticker3, p_sticker2, p_sticker1 };

        int yeild = 0;

        for (String p : ps) {
            matcher = Pattern.compile(p).matcher(sticker);
            if (!matcher.find()) {
                continue;
            }

            int gc = matcher.groupCount();
            if (gc == 1) {
                yeild = m_sticker1(matcher);
                break;
            }
            if (gc == 3) {
                yeild = m_sticker3(matcher);
                break;
            }
            if (gc == 5) {
                yeild = m_sticker5(matcher);
                break;
            }

        }

        double amount = (yeild * prc);

        // save this to database
        Bundle b = getIntent().getExtras();
        productions p = (productions) b.getSerializable(s1.s1_productions);

        production_details pd = new production_details(p.getId(), product_name,
                sticker, prc, yeild, amount, time);

        svc_save_production_details(pd);

    }

    int m_sticker1(Matcher matcher) {
        String cnt = matcher.group(1);
        return Integer.parseInt(cnt);
    }

    int m_sticker3(Matcher matcher) {
        String tray = matcher.group(1);
        String cap = matcher.group(3);
        return Integer.parseInt(tray) * Integer.parseInt(cap);
    }

    int m_sticker5(Matcher matcher) {
        String tray = matcher.group(1);
        String cap = matcher.group(3);
        String addl = matcher.group(5);
        return ((Integer.parseInt(tray) * Integer.parseInt(cap)) + Integer
                .parseInt(addl));
    }

    // menu listener
    public boolean onCreateOptionsMenu(Menu menu) {
        new MenuInflater(getApplication()).inflate(R.menu.page3_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.page3_mnu_main) {
            tomain();
            return true;
        }
        if (item.getItemId() == R.id.page3_mnu_page2) {
            topage2();
            return true;
        }
        if( item.getItemId() == R.id.page3_mnu_load_product) {
        	LookProductTask task = new LookProductTask();
            task.execute();
        	return true;
        }
        return false;
    }

    private void topage2() {

        Bundle b = getIntent().getExtras();
        productions p = (productions) b.getSerializable(s1.s1_productions);

        Intent browse = new Intent();
        browse.setClass(Page3.this, Page2.class);
        browse.putExtra(s1.s1_productions, p);
        startActivity(browse);
    }

    private void tomain() {
        Intent browse = new Intent();
        browse.setClass(Page3.this, Main.class);
        startActivity(browse);
    }

    private void hlp_clean() {
        et_sticker.setText("");
    }

    void on_go1() {
        // check the inputs

        if (!check_actv_product(actv_product.getText().toString())) {
            String msg = "input format incorrect \n ex. product@99";
            // Toast.makeText(this, msg, 3000).show();
            hlp_alert_dialog_show(msg);
            actv_product.requestFocus();
            return;
        }

        if (!check_et_sticker(et_sticker.getText().toString())) {
            String msg = "input format incorrect \n ex. 10x10+1";
            // Toast.makeText(this, "input format incorrect \n ex. 10x10+1",
            // 3000).show();
            hlp_alert_dialog_show(msg);
            et_sticker.requestFocus();
            return;
        }

        int h = tp_time.getCurrentHour();
        int m = tp_time.getCurrentMinute();
        Date date = new Date(0, 0, 0, h, m);
        String product = actv_product.getText().toString();
        String sticker = et_sticker.getText().toString();

        // filter and save to database
        hlp_process_product_entry(date, product, sticker);

        Bundle b = getIntent().getExtras();
        productions p = (productions) b.getSerializable(s1.s1_productions);

        // go to page 2
        Intent browse = new Intent();
        browse.setClass(Page3.this, Page2.class);
        browse.putExtra(s1.s1_productions, p);
        startActivity(browse);
    }

    private void hlp_alert_dialog_show(String message) {
        AlertDialog.Builder alert_dialog_builder = new AlertDialog.Builder(this);
        alert_dialog_builder.setMessage(message).setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });

        alert_dialog = alert_dialog_builder.create();
        alert_dialog.show();
    }

    private boolean check_et_sticker(String s) {
        return s
                .matches("(\\d*)([\\*|x|X])(\\d*)(\\+)(\\d*)|(\\d*)([\\*|x|X])(\\d*)|(\\d*)");
    }

    private boolean check_actv_product(String s) {
        return s.matches("([\\d|\\s|\\w|%|/|-]*)([@])(\\d*[.]\\d*)");
    }

}
